//
//  UserRegistInfo.swift
//  App
//
//  Created by 汤泽川 on 2019/3/26.
//

import Foundation
import Vapor
import FluentMySQL
import Regex

struct UserRegisterInfo : BaseModel {
    var createdAt: Date?
    var updatedAt: Date?
    var id : Int?
    
    var username : String
    var password : String
    var email : String
    var verifyCode : String?
    // TODO:密码加密存储
}

extension UserRegisterInfo {
    // 注册校验
    public func checkRegisterEnable(req : Request) throws -> Future<Bool> {
        return self.validateExist(req: req).flatMap({
            isExist in
            if isExist {
                throw APIError.userExistError
            }
            if self.validateUsername() == false {
                throw APIError.illegalUsernameError
            }
            if self.validatePassword() == false {
                throw APIError.illegalPasswordError
            }
            guard self.verifyCode != nil else {
                throw APIError.emptyVerifyCodeError
            }
            return try self.validateVerifyCode(req: req).map({
                validateVerifyCode in
                if validateVerifyCode {
                    return true
                } else {
                    throw APIError.illegalVerifyCodeError
                }
            }).catchMap({ (error) -> (Bool) in
                throw error
            })
        }).catchFlatMap({
            error in
            throw error
        })
        
    }
    
    // 检验用户是否已存在
    public func validateExist(req : Request) -> Future<Bool> {
        return UserRegisterInfo.query(on: req).filter(\.username == self.username).first().map({
            user in
            if user != nil {
                return true
            }
            return false
        })
    }
    
    // 检验用户名是否合法
    public func validateUsername() -> Bool {
        // 6-8位的纯字母
        return self.username =~ "^[A-Za-z]{6,8}$"
    }
    
    // 检验密码是否合法
    public func validatePassword() -> Bool {
        // 6-18位的字母数字组合
        return self.password =~ "^[A-Za-z0-9]{6,18}$"
    }
    
    // 检验验证码是否正确
    public func validateVerifyCode(req : Request) throws -> Future<Bool> {
        guard let verifyCode = self.verifyCode else {
            throw APIError.emptyVerifyCodeError
        }
        return VerifyCode.query(on: req).filter(\.code == verifyCode).filter(\.email == self.email).first().map({
            resultCode in
            guard let resultCode = resultCode else {
                return false
            }
            _ = resultCode.delete(on: req)
            return true
        }).catchMap({ error in
            throw error
        })
    }
}
